<template>
  <div class="upload-container">
    <view
      class="update-img"
      :style="`
        width: ${width}px;
        height: ${height}px
      `" 
      v-loading="isLoading" 
      @click.stop="uploadFile"
    >
      <div v-if="modelValue" class="image">
        <el-image :src="modelValue" fit="fill" />
      </div>
    </view>
    <view class="upload-canvas" id="upload-canvas" v-if="needWatermarkImg">
      <image class="img" :src="imgUrl"></image>
      <view class="text">海米AI</view>
    </view>
  </div>
</template>

<script>
  import html2canvas from "html2canvas";
  export default {
    name: 'UniImageUpload',
    props: {
      modelValue: {
        type: String,
        default: ''
      },
      mediaType: {
        type: String,
        default: 'image'
      },
      needWatermarkImg: {
        type: Boolean,
        default: false
      },
      width: {
        type: Number,
        default: 150
      },
      height: {
        type: Number,
        default: 150
      }
    },
    data() {
      return {
        dialogVisible: false,
        isLoading: false,
        imgUrl: ''
      }
    },
    methods: {
      // 移除
      remove() {
        this.$emit('update:data', '')
      },
      uploadFile() {
        let type = this.mediaType;
        let fileType;
        let extension = [];
        if (type === "image") {
          extension = ["png", "jpg", "jpeg", "gif", "bmp", "svg", "webp", "jfif", "dpg"];
          fileType = "image";
        } else if (type === "video") {
          extension = ["avi", "mp3", "mp4", "3gp", "mov", "rmvb", "rm", "flv", "mkv", "wmv", "m3u8", "mpg", "mpeg",
            "dat", "asf"
          ];
          fileType = "video";
        } else if (type === "other") {
          extension = ["txt", "pdf", "xls", "xlsx", "ppt", "pptx", "doc", "docx", "rar", "zip"];
        }
        uni.chooseFile({
          extension,
          success: async res => {
            this.isLoading = true
            this.imgUrl = res.tempFilePaths[0]
            const uploadRes = await vk.uploadFile({
              filePath: res.tempFilePaths[0],
              file: res.tempFiles[0],
              needSave: true,
              fileType
            });
            this.$emit('success', uploadRes.url)
            this.$emit('update:modelValue', uploadRes.url)
            if (this.needWatermarkImg) {
              this.saveMaskImg()
            }
            this.isLoading = false
          }
        });
      },
      async saveMaskImg() {
        const canvas = await html2canvas(document.querySelector('#upload-canvas'));
       
        let imgData = canvas.toDataURL('image/jpeg', 1)
        // Base64 编码的图片转成二进制图片
        const byteString = window.atob(imgData.split(',')[1]);
        const mimeString = imgData.split(',')[0].split(':')[1].split(';')[0];
        const ab = new ArrayBuffer(byteString.length);
        const ia = new Uint8Array(ab);
        for (let i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
        }
        const blob = new Blob([ab], { type: mimeString });
        let blobUrl = URL.createObjectURL(blob);
        const uploadRes = await vk.uploadFile({
          filePath:blobUrl,
          file: blob,
          needSave: true,
          fileType: 'image'
        });
        this.$emit('unpdateWatermarkUrl', uploadRes.url)
      },
      dataURLtoBlob(dataurl) {
        var arr = dataurl.split(','),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], {
          type: mime
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .update-img {
    width: 150px;
    height: 150px;
    border: 1px solid #e4e2e2;
    cursor: pointer;
    background-color: transparent;
    transition: all 0.25s;
    position: relative;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    color: #d5d5de;

    &::before {
      line-height: 1;
      font-size: 45px;
      content: "+";
    }

    &::after {
      content: "上传";
      font-size: 12px;
    }
  }

  .upload-canvas {
    width: 500px;
    height: 500px;
    position: absolute;
    z-index: -9;
    left: -9999px;

    .img {
      width: 500px;
      height: 500px;
    }

    .text {
      color: #999;
      font-size: 60px;
      font-weight: bold;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%)
    }
  }
</style>